﻿using FlashGameSite.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FlashGameSite
{
    public partial class FormMessageConv : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.Cookies.AllKeys.Contains("fguid"))
            {
                Response.Redirect("Login.aspx?prev=Messages.aspx");
            }

            if (!Request.QueryString.AllKeys.Contains("convid"))
            {
                Response.Redirect("Messages.aspx");
            }

            if(!IsPostBack)
            {
                GetMessages();
                GetTitle();
            }
        }

        private void GetTitle()
        {
            long userId = Convert.ToInt64(Request.Cookies["fguid"].Value.Split('/')[0]);
            string messageGuid = Request.QueryString["convid"];
            using (FlashGamesDataContext dataContext = new FlashGamesDataContext())
            {
                string username = dataContext.GetPartnerUsername(messageGuid, userId);
                htitle.InnerText = string.Format("Conversation with {0}", username);
            }
        }

        private void GetMessages()
        {
            long userId = Convert.ToInt64(Request.Cookies["fguid"].Value.Split('/')[0]);
            string messageGuid = Request.QueryString["convid"];

            using (FlashGamesDataContext dataContext = new FlashGamesDataContext())
            {
                GridMessages.DataSource = dataContext.GetMessageConversations(messageGuid, userId);
                GridMessages.DataBind();
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            long userId = Convert.ToInt64(Request.Cookies["fguid"].Value.Split('/')[0]);
            string messageGuid = Request.QueryString["convid"];
            using (FlashGamesDataContext dataContext = new FlashGamesDataContext())
            {
                dataContext.AddMessage(messageGuid, txtMessageText.Text, userId);
            }

            GetMessages();
            txtMessageText.Text = "";
        }
    }
}